'use strict';

const babelify = require('babelify');
const externalArr = ['jquery'];

module.exports = function(grunt) {
  // configure grunt
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    jshint: {
      files: [
        '**/*.js',
        '!node_modules/**/*',
        '!dist/**/*',
      ],
      options: {
        jshintrc: '.jshintrc'
      }
    },

    // remove all previous browserified builds
    clean: {
      dist: ['./dist/**/*'],
    },

    browserify: {
      vendor: {
        src: [],
        dest: './dist/<%= pkg.name %>.vendor.js',
        options: {
          require: externalArr
        }
      },

      // 直接将变量暴漏给window
      standalone: {
        src: ['./src/<%= pkg.name %>.js'],
        dest: './dist/<%= pkg.name %>.standalone.js',
        options: {
          browserifyOptions: {
            standalone: '<%= pkg.name %>'
          },
          transform: [babelify],
          external: externalArr
        }
      },

      require: {
        src: ['./src/<%= pkg.name %>.js'],
        dest: './dist/<%= pkg.name %>.require.js',
        options: {
          // require(<%= pkg.name %>)
          alias: [
            './src/<%= pkg.name %>.js:<%= pkg.name %>',
          ],
          transform: [babelify],
          external: externalArr
        }
      },
    },

    // Uglify browser libs
    uglify: {
      dist: {
        files: {
          './dist/<%= pkg.name %>.vendor.min.js':
            ['<%= browserify.vendor.dest %>'],
          './dist/<%= pkg.name %>.standalone.min.js':
              ['<%= browserify.standalone.dest %>'],
          './dist/<%= pkg.name %>.require.min.js':
              ['<%= browserify.require.dest %>'],
        }
      }
    },

    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['default']
    },

  });

  // Load plug-ins
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-eslint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-watch');

  // define tasks
  grunt.registerTask('default', [
    'jshint',
    'clean',
    'browserify',
    'uglify',
  ]);
};
